import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    shopId: '',
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_SHOP_ID: (state, shopId) => {
    state.shopId = shopId
  }
}

const actions = {
  // user login
  saveToken({ commit }, data) {
    commit('SET_TOKEN', data.token)
    setToken(data.token)
  },

  // get user info
  saveUserInfo({ commit, state },data) {
    const { shopName, logo, id } = data
    commit('SET_NAME', shopName)
    commit('SET_AVATAR', logo)
    commit('SET_SHOP_ID', id)
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

